<template>
  <div class="usage-statistics">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form">
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="searchForm.licensePlate" placeholder="请输入车牌号" clearable></el-input>
        </el-form-item>
        <el-form-item label="车辆品牌" prop="brandId">
          <el-select v-model="searchForm.brandId" placeholder="请选择车辆品牌" clearable>
            <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型" prop="type">
          <el-select v-model="searchForm.type" placeholder="请选择车辆类型" clearable>
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间段" prop="dateRange">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div slot="header" class="clearfix">
            <span>平均租赁次数</span>
          </div>
          <div class="stat-value">{{ stats.avgRentalCount }}</div>
          <div class="stat-desc">次/车辆</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div slot="header" class="clearfix">
            <span>平均使用时长</span>
          </div>
          <div class="stat-value">{{ stats.avgRentalDuration }}</div>
          <div class="stat-desc">天/车辆</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div slot="header" class="clearfix">
            <span>平均行驶里程</span>
          </div>
          <div class="stat-value">{{ stats.avgMileage }}</div>
          <div class="stat-desc">公里/车辆</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 使用情况图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>车辆使用频率TOP10</span>
          </div>
          <div id="frequency-chart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>车辆里程TOP10</span>
          </div>
          <div id="mileage-chart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>车辆使用时长与里程分析</span>
          </div>
          <div id="scatter-chart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <div class="table-header">
        <span class="table-title">车辆使用详情</span>
        <el-button type="primary" icon="el-icon-download" @click="exportData">导出数据</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :row-class-name="getRowClassName"
      >
        <el-table-column prop="vehicleId" label="车辆ID" width="80" align="center"></el-table-column>
        <el-table-column prop="licensePlate" label="车牌号" width="120" align="center"></el-table-column>
        <el-table-column prop="vehicleName" label="车辆名称" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="brandName" label="品牌" width="100"></el-table-column>
        <el-table-column prop="typeName" label="类型" width="100"></el-table-column>
        <el-table-column prop="rentalCount" label="租赁次数" width="100" align="center"></el-table-column>
        <el-table-column prop="totalDuration" label="总使用时长(天)" width="120" align="center"></el-table-column>
        <el-table-column prop="avgDuration" label="平均租期(天)" width="120" align="center"></el-table-column>
        <el-table-column prop="totalMileage" label="总里程(公里)" width="120" align="center"></el-table-column>
        <el-table-column prop="avgMileage" label="平均里程(公里/天)" width="150" align="center"></el-table-column>
        <el-table-column label="损耗评估" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="getWearLevelType(scope.row.wearLevel)">
              {{ getWearLevelLabel(scope.row.wearLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="异常里程" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.hasAbnormalMileage" type="danger">异常</el-tag>
            <span v-else>正常</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-data-analysis" @click="viewDetail(scope.row)">详情分析</el-button>
            <el-button size="mini" type="warning" icon="el-icon-warning" v-if="scope.row.wearLevel >= 3" @click="evaluateWear(scope.row)">损耗评估</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParams.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 详情分析对话框 -->
    <el-dialog title="车辆使用详情分析" :visible.sync="detailDialogVisible" width="900px">
      <div v-loading="detailLoading">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="车牌号">{{ detailInfo.licensePlate }}</el-descriptions-item>
          <el-descriptions-item label="车辆名称">{{ detailInfo.vehicleName }}</el-descriptions-item>
          <el-descriptions-item label="品牌">{{ detailInfo.brandName }}</el-descriptions-item>
          <el-descriptions-item label="总租赁次数">{{ detailInfo.rentalCount }}次</el-descriptions-item>
          <el-descriptions-item label="总使用时长">{{ detailInfo.totalDuration }}天</el-descriptions-item>
          <el-descriptions-item label="总行驶里程">{{ detailInfo.totalMileage }}公里</el-descriptions-item>
        </el-descriptions>

        <div id="usage-trend-chart" class="chart detail-chart"></div>
        
        <el-table
          :data="detailInfo.rentalRecords || []"
          border
          stripe
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column prop="orderId" label="订单号" width="150"></el-table-column>
          <el-table-column prop="customerName" label="租客姓名" width="120"></el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="170"></el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="170"></el-table-column>
          <el-table-column prop="duration" label="租期(天)" width="100"></el-table-column>
          <el-table-column prop="mileage" label="行驶里程(公里)" width="150"></el-table-column>
          <el-table-column prop="dailyMileage" label="日均里程(公里)" width="150"></el-table-column>
          <el-table-column label="里程状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isAbnormal" type="danger">异常</el-tag>
              <el-tag v-else type="success">正常</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 损耗评估对话框 -->
    <el-dialog title="车辆损耗评估" :visible.sync="wearDialogVisible" width="600px">
      <div v-loading="wearLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="车牌号">{{ wearInfo.licensePlate }}</el-descriptions-item>
          <el-descriptions-item label="车辆名称">{{ wearInfo.vehicleName }}</el-descriptions-item>
          <el-descriptions-item label="出厂年份">{{ wearInfo.productionYear }}</el-descriptions-item>
          <el-descriptions-item label="车辆年龄">{{ wearInfo.age }}年</el-descriptions-item>
          <el-descriptions-item label="总行驶里程">{{ wearInfo.totalMileage }}公里</el-descriptions-item>
          <el-descriptions-item label="总使用时长">{{ wearInfo.totalDuration }}天</el-descriptions-item>
          <el-descriptions-item label="当前损耗等级">
            <el-tag :type="getWearLevelType(wearInfo.wearLevel)">
              {{ getWearLevelLabel(wearInfo.wearLevel) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预估剩余使用寿命">{{ wearInfo.remainingLife }}年</el-descriptions-item>
        </el-descriptions>

        <div class="wear-progress">
          <div class="wear-title">损耗进度</div>
          <el-progress :percentage="wearInfo.wearPercentage" :status="getWearStatus(wearInfo.wearLevel)" :stroke-width="20"></el-progress>
        </div>

        <div class="wear-factors">
          <div class="wear-title">损耗因素分析</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="factor-item">
                <div class="factor-name">里程损耗</div>
                <el-progress type="dashboard" :percentage="wearInfo.mileageWearPercentage" :stroke-width="8"></el-progress>
                <div class="factor-desc">{{ getMileageWearDesc(wearInfo.mileageWearPercentage) }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="factor-item">
                <div class="factor-name">时间损耗</div>
                <el-progress type="dashboard" :percentage="wearInfo.timeWearPercentage" :stroke-width="8"></el-progress>
                <div class="factor-desc">{{ getTimeWearDesc(wearInfo.timeWearPercentage) }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="wear-suggestion">
          <div class="wear-title">评估建议</div>
          <div class="suggestion-content">{{ wearInfo.suggestion }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="wearDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="generateWearReport">生成评估报告</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import * as echarts from 'echarts'

export default {
  name: 'UsageStatistics',
  data() {
    return {
      // 搜索表单
      searchForm: {
        licensePlate: '',
        brandId: '',
        type: '',
        dateRange: []
      },
      // 分页参数
      pageParams: {
        current: 1,
        size: 10
      },
      // 表格数据
      tableData: [],
      total: 0,
      loading: false,
      // 统计数据
      stats: {
        avgRentalCount: 0,
        avgRentalDuration: 0,
        avgMileage: 0
      },
      // 图表对象
      frequencyChart: null,
      mileageChart: null,
      scatterChart: null,
      usageTrendChart: null,
      // 详情对话框
      detailDialogVisible: false,
      detailLoading: false,
      detailInfo: {},
      // 损耗评估对话框
      wearDialogVisible: false,
      wearLoading: false,
      wearInfo: {},
      // 选项
      brandOptions: [],
      typeOptions: [
        { value: 1, label: '经济型' },
        { value: 2, label: '舒适型' },
        { value: 3, label: '豪华型' },
        { value: 4, label: 'SUV' },
        { value: 5, label: 'MPV' }
      ],
      wearLevelOptions: [
        { value: 1, label: '轻微', type: 'success' },
        { value: 2, label: '正常', type: 'info' },
        { value: 3, label: '中度', type: 'warning' },
        { value: 4, label: '严重', type: 'danger' },
        { value: 5, label: '极重', type: 'danger' }
      ]
    }
  },
  created() {
    this.fetchBrands()
    this.fetchData()
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  beforeDestroy() {
    this.disposeCharts()
    window.removeEventListener('resize', this.resizeCharts)
  },
  methods: {
    // 获取品牌列表
    async fetchBrands() {
      try {
        const res = await request.get('/car-vehicle/vehicle-brands/list')
        if (res.code === 0) {
          this.brandOptions = res.data || []
        }
      } catch (error) {
        // 如果错误消息是"操作成功"，说明这是一个误报的错误
        // 这可能是由于后端返回了成功状态但前端误判为错误
        if (error.message === '操作成功') {
          console.log('获取品牌列表成功，但被误判为错误')
          // 可以尝试从error对象中提取数据
          if (error.response && error.response.data && error.response.data.data) {
            this.brandOptions = error.response.data.data || []
          }
        } else {
          console.error('获取品牌列表失败', error)
        }
      }
    },
    // 获取表格数据
    async fetchData() {
      this.loading = true
      try {
        // 构建查询参数
        const params = {
          ...this.pageParams,
          licensePlate: this.searchForm.licensePlate,
          brandId: this.searchForm.brandId,
          type: this.searchForm.type,
          startDate: this.searchForm.dateRange && this.searchForm.dateRange.length > 0 ? this.searchForm.dateRange[0] : null,
          endDate: this.searchForm.dateRange && this.searchForm.dateRange.length > 0 ? this.searchForm.dateRange[1] : null
        }
        
        const res = await request.get('/car-vehicle/vehicle/usage/statistics', { params })
        if (res.code === 0) {
          this.tableData = res.data.records || []
          this.total = res.data.total || 0
          this.stats = res.data.stats || {
            avgRentalCount: 0,
            avgRentalDuration: 0,
            avgMileage: 0
          }
          
          this.$nextTick(() => {
            this.updateCharts(res.data.chartData || {})
          })
        }
      } catch (error) {
        // 如果错误消息是"操作成功"，说明这是一个误报的错误
        if (error.message === '操作成功') {
          console.log('获取使用统计数据成功，但被误判为错误')
          // 尝试从error对象中提取数据
          if (error.response && error.response.data) {
            const data = error.response.data.data || {}
            this.tableData = data.records || []
            this.total = data.total || 0
            this.stats = data.stats || {
              avgRentalCount: 0,
              avgRentalDuration: 0,
              avgMileage: 0
            }
            
            this.$nextTick(() => {
              this.updateCharts(data.chartData || {})
            })
          }
        } else {
          console.error('获取使用统计数据失败', error)
          this.$message.error('获取使用统计数据失败')
        }
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleSearch() {
      this.pageParams.current = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    // 分页大小变化
    handleSizeChange(size) {
      this.pageParams.size = size
      this.fetchData()
    },
    // 当前页变化
    handleCurrentChange(current) {
      this.pageParams.current = current
      this.fetchData()
    },
    // 导出数据
    exportData() {
      const params = {
        licensePlate: this.searchForm.licensePlate,
        brandId: this.searchForm.brandId,
        type: this.searchForm.type,
        startDate: this.searchForm.dateRange && this.searchForm.dateRange.length > 0 ? this.searchForm.dateRange[0] : null,
        endDate: this.searchForm.dateRange && this.searchForm.dateRange.length > 0 ? this.searchForm.dateRange[1] : null
      }
      
      request({
        url: '/car-vehicle/vehicle/usage/export',
        method: 'get',
        params,
        responseType: 'blob'
      }).then(res => {
        // 直接使用res作为blob数据，因为responseType为'blob'时，axios不会解析响应
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '车辆使用统计数据.xlsx'
        link.click()
        URL.revokeObjectURL(link.href)
      }).catch(err => {
        console.error('导出数据失败', err)
        this.$message.error('导出数据失败')
      })
    },
    // 查看详情
    async viewDetail(row) {
      this.detailDialogVisible = true
      this.detailLoading = true
      this.detailInfo = { ...row }
      
      try {
        const res = await request.get(`/car-vehicle/vehicle/usage/detail/${row.vehicleId}`)
        if (res.code === 0) {
          this.detailInfo = { ...this.detailInfo, ...res.data }
          
          this.$nextTick(() => {
            this.renderUsageTrendChart(res.data.trendData || [])
          })
        }
      } catch (error) {
        // 如果错误消息是"操作成功"，说明这是一个误报的错误
        if (error.message === '操作成功') {
          console.log('获取使用详情成功，但被误判为错误')
          // 尝试从error对象中提取数据
          if (error.response && error.response.data && error.response.data.data) {
            const data = error.response.data.data
            this.detailInfo = { ...this.detailInfo, ...data }
            
            this.$nextTick(() => {
              this.renderUsageTrendChart(data.trendData || [])
            })
          }
        } else {
          console.error('获取使用详情失败', error)
          this.$message.error('获取使用详情失败')
        }
      } finally {
        this.detailLoading = false
      }
    },
    // 损耗评估
    async evaluateWear(row) {
      this.wearDialogVisible = true
      this.wearLoading = true
      this.wearInfo = { ...row }
      
      try {
        const res = await request.get(`/car-vehicle/vehicle/usage/wear/${row.vehicleId}`)
        if (res.code === 0) {
          this.wearInfo = { ...this.wearInfo, ...res.data }
        }
      } catch (error) {
        // 如果错误消息是"操作成功"，说明这是一个误报的错误
        if (error.message === '操作成功') {
          console.log('获取损耗评估成功，但被误判为错误')
          // 尝试从error对象中提取数据
          if (error.response && error.response.data && error.response.data.data) {
            this.wearInfo = { ...this.wearInfo, ...error.response.data.data }
          }
        } else {
          console.error('获取损耗评估失败', error)
          this.$message.error('获取损耗评估失败')
        }
      } finally {
        this.wearLoading = false
      }
    },
    // 生成损耗评估报告
    generateWearReport() {
      request({
        url: `/car-vehicle/vehicle/usage/wear/report/${this.wearInfo.vehicleId}`,
        method: 'get',
        responseType: 'blob'
      }).then(res => {
        // 直接使用res作为blob数据，因为responseType为'blob'时，axios不会解析响应
        const blob = new Blob([res], { type: 'application/pdf' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = `${this.wearInfo.licensePlate}损耗评估报告.pdf`
        link.click()
        URL.revokeObjectURL(link.href)
      }).catch(err => {
        console.error('生成评估报告失败', err)
        this.$message.error('生成评估报告失败')
      })
    },
    // 获取行样式
    getRowClassName({ row }) {
      if (row.hasAbnormalMileage) {
        return 'abnormal-row'
      }
      if (row.wearLevel >= 4) {
        return 'critical-wear-row'
      }
      if (row.wearLevel === 3) {
        return 'warning-wear-row'
      }
      return ''
    },
    // 获取损耗等级标签
    getWearLevelLabel(level) {
      const option = this.wearLevelOptions.find(item => item.value === level)
      return option ? option.label : '未知'
    },
    // 获取损耗等级类型
    getWearLevelType(level) {
      const option = this.wearLevelOptions.find(item => item.value === level)
      return option ? option.type : 'info'
    },
    // 获取损耗状态
    getWearStatus(level) {
      if (level >= 4) return 'exception'
      if (level === 3) return 'warning'
      return ''
    },
    // 获取里程损耗描述
    getMileageWearDesc(percentage) {
      if (percentage >= 80) return '里程损耗严重，建议检修'
      if (percentage >= 60) return '里程损耗中度，需关注'
      if (percentage >= 40) return '里程损耗正常，定期保养'
      return '里程损耗轻微'
    },
    // 获取时间损耗描述
    getTimeWearDesc(percentage) {
      if (percentage >= 80) return '时间损耗严重，建议更新'
      if (percentage >= 60) return '时间损耗中度，需关注'
      if (percentage >= 40) return '时间损耗正常，定期检查'
      return '时间损耗轻微'
    },
    // 初始化图表
    initCharts() {
      // 使用频率图表
      this.frequencyChart = echarts.init(document.getElementById('frequency-chart'))
      
      // 里程图表
      this.mileageChart = echarts.init(document.getElementById('mileage-chart'))
      
      // 散点图
      this.scatterChart = echarts.init(document.getElementById('scatter-chart'))
      
      // 监听窗口大小变化
      window.addEventListener('resize', this.resizeCharts)
      
      // 初始化图表数据
      this.updateCharts({})
    },
    // 更新图表数据
    updateCharts(chartData) {
      // 使用频率图表
      const frequencyOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '租赁次数'
        },
        yAxis: {
          type: 'category',
          data: (chartData.frequencyData || []).map(item => item.licensePlate),
          axisLabel: {
            formatter: function(value) {
              return value.length > 8 ? value.slice(0, 8) + '...' : value
            }
          }
        },
        series: [{
          name: '租赁次数',
          type: 'bar',
          data: (chartData.frequencyData || []).map(item => item.count),
          itemStyle: {
            color: function(params) {
              // 颜色渐变
              const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', 
                                '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
              return colorList[params.dataIndex % colorList.length];
            }
          }
        }]
      }
      this.frequencyChart.setOption(frequencyOption)
      
      // 里程图表
      const mileageOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            return `${params[0].name}<br/>总里程: ${params[0].value} 公里`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '总里程(公里)'
        },
        yAxis: {
          type: 'category',
          data: (chartData.mileageData || []).map(item => item.licensePlate),
          axisLabel: {
            formatter: function(value) {
              return value.length > 8 ? value.slice(0, 8) + '...' : value
            }
          }
        },
        series: [{
          name: '总里程',
          type: 'bar',
          data: (chartData.mileageData || []).map(item => item.mileage),
          itemStyle: {
            color: function(params) {
              // 颜色渐变
              const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', 
                                '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
              return colorList[params.dataIndex % colorList.length];
            }
          }
        }]
      }
      this.mileageChart.setOption(mileageOption)
      
      // 散点图
      const scatterOption = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            return `${params.data.name}<br/>使用时长: ${params.data.duration} 天<br/>总里程: ${params.data.mileage} 公里`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '使用时长(天)'
        },
        yAxis: {
          type: 'value',
          name: '总里程(公里)'
        },
        series: [{
          type: 'scatter',
          data: (chartData.scatterData || []).map(item => ({
            name: item.licensePlate,
            value: [item.duration, item.mileage],
            duration: item.duration,
            mileage: item.mileage,
            symbolSize: 15
          })),
          symbolSize: function(data) {
            // 使用自定义大小
            return Math.sqrt(data[0] * data[1]) / 50 + 5
          },
          itemStyle: {
            color: function(params) {
              // 异常里程标记为红色
              if (params.data.abnormal) {
                return '#c23531'
              }
              return '#5470c6'
            }
          }
        }]
      }
      this.scatterChart.setOption(scatterOption)
    },
    // 渲染使用趋势图表
    renderUsageTrendChart(trendData) {
      if (!trendData || trendData.length === 0) return
      
      if (!this.usageTrendChart) {
        this.usageTrendChart = echarts.init(document.getElementById('usage-trend-chart'))
      }
      
      const dates = trendData.map(item => item.date)
      const mileages = trendData.map(item => item.mileage)
      const durations = trendData.map(item => item.duration)
      
      const option = {
        title: {
          text: '使用趋势分析',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['行驶里程', '使用时长'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: dates
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '里程(公里)',
            position: 'left',
          },
          {
            type: 'value',
            name: '时长(天)',
            position: 'right',
          }
        ],
        series: [
          {
            name: '行驶里程',
            type: 'line',
            yAxisIndex: 0,
            data: mileages,
            smooth: true,
            areaStyle: {}
          },
          {
            name: '使用时长',
            type: 'line',
            yAxisIndex: 1,
            data: durations,
            smooth: true,
            areaStyle: {}
          }
        ]
      }
      
      this.usageTrendChart.setOption(option)
    },
    // 调整图表大小
    resizeCharts() {
      if (this.frequencyChart) this.frequencyChart.resize()
      if (this.mileageChart) this.mileageChart.resize()
      if (this.scatterChart) this.scatterChart.resize()
      if (this.usageTrendChart) this.usageTrendChart.resize()
    },
    // 销毁图表
    disposeCharts() {
      if (this.frequencyChart) {
        this.frequencyChart.dispose()
        this.frequencyChart = null
      }
      if (this.mileageChart) {
        this.mileageChart.dispose()
        this.mileageChart = null
      }
      if (this.scatterChart) {
        this.scatterChart.dispose()
        this.scatterChart = null
      }
      if (this.usageTrendChart) {
        this.usageTrendChart.dispose()
        this.usageTrendChart = null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.usage-statistics {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
    }
  }
  
  .stat-cards {
    margin-bottom: 20px;
    
    .stat-card {
      text-align: center;
      
      .stat-value {
        font-size: 28px;
        font-weight: bold;
        color: #409EFF;
      }
      
      .stat-desc {
        color: #909399;
        font-size: 14px;
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      .chart {
        height: 350px;
      }
    }
  }
  
  .table-card {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .table-title {
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  .detail-chart {
    height: 300px;
    margin: 20px 0;
  }
  
  .wear-progress {
    margin: 20px 0;
    
    .wear-title {
      font-weight: bold;
      margin-bottom: 10px;
    }
  }
  
  .wear-factors {
    margin: 20px 0;
    
    .wear-title {
      font-weight: bold;
      margin-bottom: 10px;
    }
    
    .factor-item {
      text-align: center;
      
      .factor-name {
        font-weight: bold;
        margin-bottom: 10px;
      }
      
      .factor-desc {
        margin-top: 10px;
        color: #606266;
      }
    }
  }
  
  .wear-suggestion {
    margin: 20px 0;
    
    .wear-title {
      font-weight: bold;
      margin-bottom: 10px;
    }
    
    .suggestion-content {
      padding: 10px;
      background-color: #f5f7fa;
      border-radius: 4px;
      line-height: 1.6;
    }
  }
}

// 表格行样式
:deep(.abnormal-row) {
  background-color: #fef0f0;
}

:deep(.critical-wear-row) {
  background-color: #fde2e2;
}

:deep(.warning-wear-row) {
  background-color: #fdf6ec;
}
</style> 